package com.xin.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.xin.entity.SOrg;
import com.xin.entity.SRoleOrg;
import com.xin.entity.STeacherRole;
import com.xin.mapper.SRoleOrgDao;
import com.xin.mapper.STeacherRoleDao;
import com.xin.service.SRoleOrgService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 角色组织关系表 服务实现类
 * </p>
 *
 * @author l1
 * @since 2017-12-05
 */
@Service
public class SRoleOrgServiceImpl extends ServiceImpl<SRoleOrgDao, SRoleOrg> implements SRoleOrgService {

    @Autowired
    private STeacherRoleDao sTeacherRoleDao;

    @Autowired
    private SRoleOrgDao sRoleOrgDao;


    @Override
    public List<SOrg> findOrgsByTeacherId(String id) {
        List<JSONObject> roles = sTeacherRoleDao.findRolesByTeacherId(id);
        List<Integer> roleIds = new ArrayList<>();
        roles.forEach(role->{
            Integer roleId = role.getInteger("id");
            roleIds.add(roleId);
        });
        if(roleIds.isEmpty()) return  null;
        return sRoleOrgDao.findOrgByRoles(roleIds);
    }

    @Override
    public void addRoleAndOrgs(STeacherRole str, JSONArray nodesArray) {
        if(nodesArray==null || nodesArray.isEmpty()) {return;}
        Integer roleId = str.getId();
        updateSRoleOrg(nodesArray, roleId);
    }

    @Transactional
    @Override
    public void editRoleAndOrgs(STeacherRole str, JSONArray nodesArray) {
        // 更新STeacherRole
        str.insertOrUpdate();
        //删除 sRoleOrg
        Integer roleId = str.getId();
        sRoleOrgDao.delete(new EntityWrapper<SRoleOrg>().eq("role_id",roleId));
        updateSRoleOrg(nodesArray, roleId);


    }

    private void updateSRoleOrg(JSONArray nodesArray, Integer roleId) {
        for (int i = 0; i < nodesArray.size(); i++) {
            JSONObject jsonObject = nodesArray.getJSONObject(i);
            Integer id = jsonObject.getInteger("id");
            Integer level = jsonObject.getInteger("level");
            SRoleOrg sRoleOrg = new SRoleOrg();
            sRoleOrg.setRoleId(roleId);
            sRoleOrg.setOrgId(id);
            sRoleOrg.setLevel(level);
            sRoleOrg.insert();
        }
    }
}
